import Playable from "../Framework/scripts/Playable";
import Watcher from "../Framework/scripts/Watcher";
import GameAssetMgr from "./GameAssetMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CookingTiledom extends cc.Component {

    /** 刷新桌面 */
    public static readonly EVENT_CREATE_ITEM = "EVENT_CREATE_ITEM";
    /** 游戏结束 */
    public static readonly EVENT_GAME_END = "EVENT_GAME_END";
   
    private itemprefab: cc.Prefab;
    private lv = 0;
    private config = [{}];
    onLoad() {
        Watcher.on(GameAssetMgr.SpriteLoadedEvent, this, this.onAssetLoaded);
        this.loadConfig().then(this.loadPrefabs.bind(this));
       
        Watcher.on(CookingTiledom.EVENT_GAME_END,this,()=>{
            Playable.INSTALL();
        });
        Playable.INIT();
    }
    start(){
        Playable.READY();
    }

    async loadConfig() {
        const context = this;
        cc.loader.loadRes('config/customConfig.json', cc.JsonAsset, (err, res) => {
            if (!err) {
                context.config = res.json;
            }
        });
    }
    async loadPrefabs() {
        const context = this;
        cc.loader.loadRes('pref/item', cc.Prefab, (err, res) => {
            if (!err) {
                context.itemprefab = res;
                context.onAssetLoaded();
            }
        });
    }

    private onAssetLoaded() {
        if (!this.itemprefab || !GameAssetMgr.instance.spriteLoaded) {
            return;
        }
        console.log("配置当前场景... ...");
        this.readConfig();
    }

    readConfig() {
        //TODO 获取当前Level
        this.lv = 0; //这里默认0

        let config = this.config[this.lv];
        Watcher.dispatch(CookingTiledom.EVENT_CREATE_ITEM, config, this.itemprefab);
    }
}
